package cn.kgc.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Student;
import cn.kgc.vue.exceptions.StudentNoException;
import cn.kgc.vue.mapper.CourseMapper;
import cn.kgc.vue.mapper.StudentMapper;
import cn.kgc.vue.service.StudentService;
import cn.kgc.vue.vo.StudentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2023-12-14 09:57:24
*/
@Service
@Slf4j
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>implements StudentService{


    @Resource
    private CourseMapper courseMapper;

    @Override
    public ResponseResult getStudentList(QueryCondition<Student> queryCondition) {

        // 1.创建分页对象
        Page<Student> studentPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotEmpty(queryCondition.getQuery().getStudentNo()),Student::getStudentNo,queryCondition.getQuery().getStudentNo())
                .eq(StringUtils.isNotEmpty(queryCondition.getQuery().getClazz()),Student::getClazz,queryCondition.getQuery().getClazz())
                .orderByDesc(Student::getSchoolYear);

        baseMapper.selectPage(studentPage,lambda);

        List<Student> records = studentPage.getRecords();

        List<StudentVO> collect = records.stream().map(student -> {

            StudentVO studentVO = new StudentVO();
            BeanUtils.copyProperties(student, studentVO);
            Integer courseId = student.getCourseId();
            String courseName = courseMapper.getById(courseId).getCourseName();

            studentVO.setCourseName(courseName);
            return studentVO;
        }).collect(Collectors.toList());

        long total = studentPage.getTotal();

        HashMap<String, Object> result = new HashMap<>();
        result.put("pageData",collect);
        result.put("total",total);

        return ResponseResult.success().data(result);
    }

    @Override
    public ResponseResult batchImportStudent(MultipartFile file)  {

        if (file.isEmpty()){
            return ResponseResult.fail().message("请添加文件");
        }

        try {
            InputStream inputStream = file.getInputStream();
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            importParams.setHeadRows(1);
            List<Student> students = ExcelImportUtil.importExcel(inputStream, Student.class, importParams);

            //  添加学生信息到数据库
            students.forEach(student -> {
                String studentNo = student.getStudentNo();
                LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
                lambda.eq(Student::getStudentNo,studentNo);
                Student stu = baseMapper.selectOne(lambda);
                if (ObjectUtils.isNotNull(stu)){
                    throw new StudentNoException();
                }
                baseMapper.insert(student);
            });
        } catch (StudentNoException e){
            throw new StudentNoException();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return ResponseResult.success().message("批量导入完成");
    }
}




